package com.css.zfzx.fxpg.modules.popgdp.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.fxpg.common.utils.ServerUtil;
import com.css.zfzx.fxpg.common.utils.VectorDataUtil;
import com.css.zfzx.fxpg.modules.popgdp.service.FxPopGDPService;
import com.css.zfzx.fxpg.modules.popgdp.viewobjects.FxPopGDPQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author andy
 * @date 2020-11-11
 */
@Slf4j
@RestController
@RequestMapping("/fxPopGDP")
public class FxPopGDPController {
    @Autowired
    private FxPopGDPService fxPopGDPService;

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    @GetMapping("/queryFxPopGDP")
    public RestResponse queryFxPopGDPs(HttpServletRequest request, FxPopGDPQueryParams queryParams) {
        String userId = ServerUtil.getUserId(request);
        RestResponse response = null;
        try{
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = fxPopGDPService.queryFxPopGDPs(queryParams, curPage, pageSize, userId);
            response = RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @DeleteMapping
    public RestResponse deleteFxPopGDPs(@RequestParam List<String> ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try{
            fxPopGDPService.deleteFxPopGDPs(ids);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        }catch (Exception e){
            String errorMessage = "删除失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @PostMapping("/importShp")
    public RestResponse importShp(@RequestParam("files") MultipartFile[] files, FxPopGDPQueryParams queryParams, HttpServletRequest request) {
        //数据校验
        if (files == null && files.length <= 0) return RestResponse.fail("上传失败，请选择文件");

        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        if ("".equals(province) ) return RestResponse.fail("请选择场地所在省份!");
        /*if ("".equals(city)) return RestResponse.fail("请选择场地所在城市!");
        if ("".equals(area)) return RestResponse.fail("请选择场地所在区县!");*/

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String jxfilename = "";
        String dbffilename = "";
        //循环处理每一个文件
        for (MultipartFile file : files) {

            String oldFileName = file.getOriginalFilename();
            String newFileName = "PG_" + (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area) + "_" + oldFileName;

            if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                jxfilename = newFileName;
            }
            if (oldFileName.contains(".dbf") && oldFileName.endsWith(".dbf")) {
                dbffilename = newFileName;
            }

            File saveFile = new File(uploadPath + newFileName);
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            try {
                File _file = new File(uploadPath + newFileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
        }
        if (!(VectorDataUtil.checkCGCS2000(uploadPath + jxfilename, null))) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");

        String userId = ServerUtil.getUserId(request);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = fxPopGDPService.importShapeFile(uploadPath + jxfilename, queryParams, userId);
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.fail("导入.dbf文件的属性的第【" + resMsg.split("#")[1] + "】条数据信息有乱码.");
        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }


}